<template>
  <div class="page-content">
    <div class="text-right p-2">
      <el-button v-if="!viewMode && sigNo" icon="el-icon-s-check" @click="handleToSign">
        签章
      </el-button>
      <el-button @click="handleDownload" v-show="pageUrl" icon="el-icon-download">下载</el-button>
      <el-button @click="getContract" v-if="!viewMode && sigNo" icon="el-icon-refresh">
        刷新
      </el-button>
    </div>
    <div class="text-center pdf-content" v-loading="loading">
      <div ref="pdfCanvas"></div>
    </div>
  </div>
</template>

<script>
import { fileSaveAs } from '@vimi/utils-tool'
import { renderPdf } from '@/common/plugins/tools/pdf'
import { getPdf, getSignUrl } from '@/credit/views/county/unionProvince/components/pdf'

export default {
  components: {},
  props: {
    contractId: String,
    queryId: {
      type: String,
      default: '',
    },
    sigNo: {
      type: String,
      default: '',
    },
    downName: {
      type: String,
      default: '合同',
    },
    viewMode: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      loading: false,
      pageUrl: '',
      blobData: '',
      pdfCanvas: {},
    }
  },
  computed: {},
  watch: {
    contractId() {
      this.getContract()
    },
  },
  created() {},
  mounted() {
    this.pdfCanvas = this.$refs.pdfCanvas
    this.getContract()
  },
  methods: {
    getContract() {
      this.pageUrl = ''
      this.blobData = ''
      this.pdfCanvas.innerHTML = ''
      if (!this.contractId) {
        return
      }
      this.loading = true
      getPdf(this.contractId, this.queryId)
        .then(data => {
          const blob = new Blob([data], { type: 'application/pdf' })
          this.blobData = blob
          this.pageUrl = window.URL.createObjectURL(blob)

          console.log(this.contractId, data) // eslint-disable-line
          return renderPdf(this.pdfCanvas, this.pageUrl)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDownload() {
      this.$emit('print', true)
      const fileName = `${this.downName}.pdf`
      fileSaveAs(this.blobData, fileName)
    },
    handleToSign() {
      const { user, org } = this.$store.getters
      getSignUrl({
        contractId: this.sigNo,
        callbackPage: `${location.href}?docId=${this.contractId}`,
        user,
        org,
      })
        .then(signUrl => {
          window.open(signUrl)
        })
        .catch(err => {
          this.$message.warning(err?.message ?? '出错了！')
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.page-content {
  border: 1px solid $border-color;
  // width: 794px;
  margin: 0 auto;
}
.pdf-content {
  min-height: 200px;
  margin: 0 auto;
}
</style>
